<template>
  <el-card class="list-view-card" shadow="never">
    <div class="table-header">
      <div class="title">
        <strong>缺陷列表</strong>
        <span class="count">共 {{ pagination.total }} 项</span>
      </div>
      <div class="header-actions">
        <el-button text class="action-button" @click="$emit('download-template')">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
        <el-upload
          class="support-upload"
          :action="''"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImportFile"
          accept=".xlsx,.xls"
        >
          <el-button text class="action-button">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        <el-button text class="action-button" @click="$emit('export')">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <el-table
      ref="tableRef"
      :data="defects"
      row-key="id"
      v-loading="loading"
      stripe
      highlight-current-row
      :style="{ flex: '1 1 auto' }"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="50" fixed="left" />
      <el-table-column label="缺陷" min-width="300" show-overflow-tooltip fixed="left">
        <template #default="{ row }">
          <div class="defect-cell">
            <div class="title-row">
              <el-link type="primary" @click="$emit('open-detail', row.id)">
                {{ row.title }}
              </el-link>
            </div>
            <div class="meta">
              <span>#{{ row.id.slice(-8) }}</span>
              <span v-if="row.project_name">{{ row.project_name }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="status" width="140" align="center" sortable="custom" column-key="status">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`status-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                :type="statusTagType(row.status)"
                class="editable-tag"
                @click.stop="handleStatusClick(row)"
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingStatus"
                placeholder="请选择状态"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleStatusChange"
                teleported
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="优先级" prop="priority" width="120" align="center" sortable="custom" column-key="priority">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`priority-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                :type="priorityTagType(row.priority)"
                class="editable-tag"
                @click.stop="handlePriorityClick(row)"
              >
                {{ getPriorityLabel(row.priority) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingPriority"
                placeholder="请选择优先级"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handlePriorityChange"
                teleported
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="严重程度" prop="severity" width="120" align="center" sortable="custom" column-key="severity">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`severity-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                :type="severityTagType(row.severity)"
                class="editable-tag"
                @click.stop="handleSeverityClick(row)"
              >
                {{ getSeverityLabel(row.severity) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingSeverity"
                placeholder="请选择严重程度"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleSeverityChange"
                teleported
              >
                <el-option
                  v-for="option in severityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="100" align="center" prop="type" sortable="custom" column-key="type">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`type-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                type="info"
                class="editable-tag"
                @click.stop="handleTypeClick(row)"
              >
                {{ getTypeLabel(row.type) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingType"
                placeholder="请选择类型"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleTypeChange"
                teleported
              >
                <el-option
                  v-for="option in typeOptions || []"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="来源" width="100" align="center" prop="source" sortable="custom" column-key="source">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`source-${row.id}`]"
            placement="top"
            :width="200"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <el-tag 
                size="small" 
                type="info"
                class="editable-tag"
                @click.stop="handleSourceClick(row)"
              >
                {{ getSourceLabel(row.source) }}
              </el-tag>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingSource"
                placeholder="请选择来源"
                style="width: 100%;"
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleSourceChange"
                teleported
              >
                <el-option
                  v-for="option in sourceOptions || []"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                  @click.stop
                  @mousedown.stop
                />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="负责人" width="150" show-overflow-tooltip prop="assignee_name" sortable="custom" column-key="assignee_id">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`assignee-${row.id}`]"
            placement="top"
            :width="250"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <div 
                class="editable-text"
                @click.stop="handleAssigneeClick(row)"
                style="display: inline-flex; align-items: center;"
              >
                <UserDisplay
                  v-if="row.assignee_id"
                  :user-id="row.assignee_id"
                  :user-name="row.assignee_name"
                  :users-map="usersMap"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未分配</span>
              </div>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingAssignee"
                placeholder="请选择负责人"
                style="width: 100%;"
                filterable
                clearable
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleAssigneeChange"
                teleported
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                  @click.stop
                  @mousedown.stop
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :users-map="usersMap"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
                <el-option label="未分配" value="" @click.stop @mousedown.stop />
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="报告人" width="150" show-overflow-tooltip prop="reporter_name" sortable="custom" column-key="reporter_id">
        <template #default="{ row }">
          <el-popover
            v-model:visible="editingPopovers[`reporter-${row.id}`]"
            placement="top"
            :width="250"
            popper-class="defect-edit-popover"
            :trigger="'manual' as any"
            :hide-after="0"
            :close-on-click-outside="false"
            :popper-options="{ strategy: 'fixed' }"
          >
            <template #reference>
              <div 
                class="editable-text"
                @click.stop="handleReporterClick(row)"
                style="display: inline-flex; align-items: center;"
              >
                <UserDisplay
                  v-if="row.reporter_id"
                  :user-id="row.reporter_id"
                  :user-name="row.reporter_name"
                  :users-map="usersMap"
                  :show-avatar="true"
                  size="small"
                />
                <span v-else style="color: #909399;">未分配</span>
              </div>
            </template>
            <div class="popover-content" @click.stop @mousedown.stop @mouseup.stop>
              <el-select
                v-model="editingReporter"
                placeholder="请选择报告人"
                style="width: 100%;"
                filterable
                clearable
                @click.stop
                @mousedown.stop
                @mouseup.stop
                @change="handleReporterChange"
                teleported
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                  @click.stop
                  @mousedown.stop
                >
                  <UserDisplay
                    :user-id="user.id"
                    :user-name="user.name"
                    :users-map="usersMap"
                    :show-avatar="true"
                    size="small"
                  />
                </el-option>
                <el-option label="未分配" value="" @click.stop @mousedown.stop>
                  <span style="color: #909399;">未分配</span>
                </el-option>
              </el-select>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="验证人" width="120" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="user-cell">
            <UserDisplay
              v-if="row.verifier_id"
              :user-id="row.verifier_id"
              :user-name="row.verifier_name"
              :users-map="usersMap"
              :show-avatar="true"
              size="small"
            />
            <span v-else class="user-name">—</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="所属项目" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.project_name || '—' }}
        </template>
      </el-table-column>

      <el-table-column label="发现日期" prop="found_date" width="160" align="center" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.found_date) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="解决日期" prop="resolved_date" width="160" align="center" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.resolved_date) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="验证日期" prop="verified_date" width="160" align="center" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.verified_date) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="完成日期" prop="completed_at" width="160" align="center" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.completed_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="实际完成时间" prop="actual_completed_at" width="160" align="center" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.actual_completed_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="版本" width="140" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.versions && row.versions.length > 0" class="versions-cell">
            <el-tag 
              v-for="version in row.versions.slice(0, 2)" 
              :key="version.id"
              size="small"
              type="primary"
              style="margin-right: 4px;"
            >
              {{ version.version_number || version.name }}
            </el-tag>
            <span v-if="row.versions.length > 2" class="more-versions">
              +{{ row.versions.length - 2 }}
            </span>
          </div>
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column label="标签" width="120" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.tags && row.tags.length > 0" class="tags-cell">
            <el-tag 
              v-for="tag in row.tags.slice(0, 2)" 
              :key="tag"
              size="small"
              style="margin-right: 4px;"
            >
              {{ tag }}
            </el-tag>
            <span v-if="row.tags.length > 2" class="more-tags">
              +{{ row.tags.length - 2 }}
            </span>
          </div>
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column label="评论" width="80" align="center">
        <template #default="{ row }">
          <span v-if="row.comment_count !== null && row.comment_count !== undefined">
            {{ row.comment_count || 0 }}
          </span>
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column label="附件" width="80" align="center">
        <template #default="{ row }">
          <span v-if="row.attachment_count !== null && row.attachment_count !== undefined">
            {{ row.attachment_count || 0 }}
          </span>
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="created_at" width="160" sortable="custom" show-overflow-tooltip :default-sort="{ prop: 'created_at', order: 'descending' }">
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.created_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" prop="updated_at" width="160" sortable="custom" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="date-time-cell">{{ formatDate(row.updated_at) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" text type="primary" @click.stop="handleSplitTask(row)">
            拆分任务
          </el-button>
          <el-button size="small" text type="danger" @click.stop="$emit('delete', row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-footer">
      <DefectBatchToolbar
        v-if="selectedIds.length > 0"
        :count="selectedIds.length"
        :status-options="statusOptionsForBatch || []"
        :priority-options="priorityOptionsForBatch || []"
        :severity-options="severityOptionsForBatch || []"
        :type-options="typeOptionsForBatch || []"
        :source-options="sourceOptionsForBatch || []"
        :users="usersForBatch || []"
        :loading="batchLoading"
        @update-status="$emit('batch-update-status')"
        @update-priority="$emit('batch-update-priority')"
        @update-severity="$emit('batch-update-severity')"
        @update-type="$emit('batch-update-type')"
        @update-source="$emit('batch-update-source')"
        @assign="$emit('batch-assign')"
        @update-reporter="$emit('batch-update-reporter')"
        @update-project="$emit('batch-update-project')"
        @remove="$emit('batch-delete')"
        @clear="$emit('batch-clear')"
      />
      <div class="table-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next"
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          @current-change="$emit('page-change', $event)"
          @size-change="$emit('page-size-change', $event)"
        />
      </div>
    </div>

  </el-card>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import dayjs from 'dayjs'
import { Download, Upload } from '@element-plus/icons-vue'
import type { ElTable } from 'element-plus'
import type { Defect } from '@/api/defect'
import type { User } from '@/types/user'
import { getDefectTypeLabel, getDefectSourceLabel } from '@/types/defect'
import { useDefectStates } from '@/composables/useDefectStates'
import { useDefectOptions } from '@/composables/useDefectOptions'
import DefectBatchToolbar from '../components/DefectBatchToolbar.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface UserOption {
  id: string
  name: string
  avatar?: string
}

const props = defineProps<{
  defects: Defect[]
  loading: boolean
  pagination: {
    page: number
    pageSize: number
    total: number
  }
  statusOptions: Array<{ value: string; label: string }>
  priorityOptions: Array<{ value: string; label: string }>
  severityOptions: Array<{ value: string; label: string }>
  typeOptions: Array<{ value: string; label: string }>
  sourceOptions?: Array<{ value: string; label: string }>
  users: UserOption[]
  selectedIds: string[]
  batchLoading?: boolean
  statusOptionsForBatch?: Array<{ value: string; label: string }>
  priorityOptionsForBatch?: Array<{ value: string; label: string }>
  severityOptionsForBatch?: Array<{ value: string; label: string }>
  typeOptionsForBatch?: Array<{ value: string; label: string }>
  sourceOptionsForBatch?: Array<{ value: string; label: string }>
  usersForBatch?: Array<{ id: string; name: string }>
}>()

const emit = defineEmits<{
  (event: 'page-change', page: number): void
  (event: 'page-size-change', size: number): void
  (event: 'select-change', ids: string[]): void
  (event: 'sort-change', data: { prop: string; order: 'ascending' | 'descending' | null }): void
  (event: 'open-detail', id: string): void
  (event: 'delete', id: string): void
  (event: 'refresh'): void
  (event: 'download-template'): void
  (event: 'import', file: File): void
  (event: 'export'): void
  (event: 'update-status', id: string, status: string): void
  (event: 'update-priority', id: string, priority: string): void
  (event: 'update-severity', id: string, severity: string): void
  (event: 'update-type', id: string, type: string): void
  (event: 'update-source', id: string, source: string): void
  (event: 'update-assignee', id: string, assigneeId: string | null): void
  (event: 'update-reporter', id: string, reporterId: string | null): void
  (event: 'split-task', item: Defect): void
  (event: 'batch-update-status'): void
  (event: 'batch-update-priority'): void
  (event: 'batch-update-severity'): void
  (event: 'batch-update-type'): void
  (event: 'batch-update-source'): void
  (event: 'batch-assign'): void
  (event: 'batch-update-reporter'): void
  (event: 'batch-update-project'): void
  (event: 'batch-delete'): void
  (event: 'batch-clear'): void
}>()

const handleImportFile = (file: any) => {
  if (file.raw) {
    emit('import', file.raw)
  }
}

const tableRef = ref<InstanceType<typeof ElTable>>()

// 同步表格头部和内容的横向滚动
let isScrolling = false
let scrollHandlersSetup = false

const handleBodyScroll = (e: Event) => {
  if (isScrolling) return
  isScrolling = true
  
  const target = e.target as HTMLElement
  const scrollLeft = target.scrollLeft
  
  if (tableRef.value) {
    const headerWrapper = tableRef.value.$el?.querySelector('.el-table__header-wrapper')
    const fixedBodyWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-body-wrapper')
    const fixedHeaderWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-header-wrapper')
    
    if (headerWrapper && headerWrapper.scrollLeft !== scrollLeft) {
      headerWrapper.scrollLeft = scrollLeft
    }
    if (fixedBodyWrapper && fixedBodyWrapper.scrollLeft !== scrollLeft) {
      fixedBodyWrapper.scrollLeft = scrollLeft
    }
    if (fixedHeaderWrapper && fixedHeaderWrapper.scrollLeft !== scrollLeft) {
      fixedHeaderWrapper.scrollLeft = scrollLeft
    }
  }
  
  requestAnimationFrame(() => {
    isScrolling = false
  })
}

const handleHeaderScroll = (e: Event) => {
  if (isScrolling) return
  isScrolling = true
  
  const target = e.target as HTMLElement
  const scrollLeft = target.scrollLeft
  
  if (tableRef.value) {
    const bodyWrapper = tableRef.value.$el?.querySelector('.el-table__body-wrapper')
    const fixedBodyWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-body-wrapper')
    const fixedHeaderWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-header-wrapper')
    
    if (bodyWrapper && bodyWrapper.scrollLeft !== scrollLeft) {
      bodyWrapper.scrollLeft = scrollLeft
    }
    if (fixedBodyWrapper && fixedBodyWrapper.scrollLeft !== scrollLeft) {
      fixedBodyWrapper.scrollLeft = scrollLeft
    }
    if (fixedHeaderWrapper && fixedHeaderWrapper.scrollLeft !== scrollLeft) {
      fixedHeaderWrapper.scrollLeft = scrollLeft
    }
  }
  
  requestAnimationFrame(() => {
    isScrolling = false
  })
}

const setupScrollSync = () => {
  if (!tableRef.value || scrollHandlersSetup) return
  
  const bodyWrapper = tableRef.value.$el?.querySelector('.el-table__body-wrapper')
  const headerWrapper = tableRef.value.$el?.querySelector('.el-table__header-wrapper')
  const fixedBodyWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-body-wrapper')
  const fixedHeaderWrapper = tableRef.value.$el?.querySelector('.el-table__fixed-header-wrapper')
  
  if (bodyWrapper && headerWrapper) {
    bodyWrapper.addEventListener('scroll', handleBodyScroll, { passive: true })
    headerWrapper.addEventListener('scroll', handleHeaderScroll, { passive: true })
    scrollHandlersSetup = true
  }
  
  // 同步固定列的滚动
  if (fixedBodyWrapper && fixedHeaderWrapper) {
    fixedBodyWrapper.addEventListener('scroll', handleBodyScroll, { passive: true })
    fixedHeaderWrapper.addEventListener('scroll', handleHeaderScroll, { passive: true })
  }
}

onMounted(() => {
  nextTick(() => {
    setupScrollSync()
  })
})

// 监听数据变化，重新设置滚动同步
watch(
  () => props.defects,
  () => {
    nextTick(() => {
      scrollHandlersSetup = false
      setupScrollSync()
    })
  }
)

const formatDate = (value?: string | null) => {
  if (!value) return '—'
  try {
    const date = dayjs(value)
    if (!date.isValid()) return '—'
    return date.format('YYYY-MM-DD HH:mm:ss')
  } catch (error) {
    console.warn('日期格式化失败:', value, error)
    return '—'
  }
}

const getStatusLabel = (value?: string | null) => {
  if (!value || value === '') return '未设置'
  const option = props.statusOptions.find(option => option.value === value)
  return option?.label ?? value
}

// 使用 composables 提供的函数
const { getPriorityName: getDefectPriorityNameFromComposable, getSeverityName: getDefectSeverityNameFromComposable, getPriorityType: getDefectPriorityTypeFromComposable, getSeverityType: getDefectSeverityTypeFromComposable } = useDefectOptions()

const getPriorityLabel = (value?: string | null) => {
  if (!value || value === '') return '未设置'
  // 优先使用 composables 提供的函数
  const priorityName = getDefectPriorityNameFromComposable(value)
  if (priorityName && priorityName !== value) return priorityName
  // 回退到 props 中的选项
  const option = props.priorityOptions.find(option => option.value === value)
  return option?.label ?? value
}

const getSeverityLabel = (value?: string | null) => {
  if (!value || value === '') return '未设置'
  // 优先使用 composables 提供的函数
  const severityName = getDefectSeverityNameFromComposable(value)
  if (severityName && severityName !== value) return severityName
  // 回退到 props 中的选项
  const option = props.severityOptions.find(option => option.value === value)
  return option?.label ?? value
}

const getTypeLabel = (value?: string | null) => {
  if (!value || value === '') return '—'
  const typeLabel = getDefectTypeLabel(value)
  if (typeLabel) return typeLabel
  const option = props.typeOptions.find(option => option.value === value)
  return option?.label ?? value
}

const getSourceLabel = (value?: string | null) => {
  if (!value || value === '') return '—'
  const sourceLabel = getDefectSourceLabel(value)
  if (sourceLabel) return sourceLabel
  const option = props.sourceOptions?.find(option => option.value === value)
  return option?.label ?? value
}

// 处理任务拆分
const handleSplitTask = (row: Defect) => {
  emit('split-task', row)
}

// 构建用户信息映射，避免重复调用用户详情接口
const usersMap = computed(() => {
  const map = new Map<string, User>()
  
  // 从缺陷列表中收集所有用户ID和名称
  props.defects.forEach(defect => {
    // 负责人
    if (defect.assignee_id) {
      if (!map.has(defect.assignee_id)) {
        map.set(defect.assignee_id, {
          id: defect.assignee_id,
          username: defect.assignee_name || '',
          name: defect.assignee_name || '',
          email: '',
          avatar: undefined,
          roles: [],
          status: 'active',
          is_verified: false,
          created_at: '',
          updated_at: ''
        } as User)
      }
    }
    
    // 报告人
    if (defect.reporter_id) {
      if (!map.has(defect.reporter_id)) {
        map.set(defect.reporter_id, {
          id: defect.reporter_id,
          username: defect.reporter_name || '',
          name: defect.reporter_name || '',
          email: '',
          avatar: undefined,
          roles: [],
          status: 'active',
          is_verified: false,
          created_at: '',
          updated_at: ''
        } as User)
      }
    }
  })
  
  return map
})

// 使用 composables 提供的函数，不再硬编码
const { getStatusType: getDefectStatusTypeFromComposable } = useDefectStates()

const statusTagType = (status?: string | null) => {
  if (!status) return 'info'
  return getDefectStatusTypeFromComposable(status)
}

const priorityTagType = (priority?: string | null) => {
  if (!priority) return 'info'
  return getDefectPriorityTypeFromComposable(priority)
}

const severityTagType = (severity?: string | null) => {
  if (!severity) return 'info'
  return getDefectSeverityTypeFromComposable(severity)
}

// 防止选择状态同步时触发递归更新的标志
const isSyncingSelection = ref(false)

const handleSelectionChange = (selection: Defect[]) => {
  // 如果正在同步选择状态，跳过事件处理，避免无限循环
  if (isSyncingSelection.value) {
    return
  }
  
  emit(
    'select-change',
    selection.map(item => item.id)
  )
}

const handleRowClick = (_row: Defect) => {
  // 点击行时不自动选择，保持用户明确选择的行为
}

const handleSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
  emit('sort-change', { prop, order })
}

// Popover 管理
const editingPopovers = ref<Record<string, boolean>>({})
const editingDefectId = ref<string | null>(null)

// 关闭所有其他 popover
const closeOtherPopovers = (exceptKey: string) => {
  Object.keys(editingPopovers.value).forEach(key => {
    if (key !== exceptKey) {
      editingPopovers.value[key] = false
    }
  })
}

// 状态编辑相关
const editingStatus = ref<string>('')

const handleStatusClick = (row: Defect) => {
  const popoverKey = `status-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingStatus.value = row.status || ''
  editingPopovers.value[popoverKey] = true
}

// 状态选择后直接更新
const handleStatusChange = (val: string) => {
  if (!editingDefectId.value) return
  if (!val) return
  
  const defectId = editingDefectId.value
  const popoverKey = `status-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingStatus.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-status', defectId, val)
}

// 优先级编辑相关
const editingPriority = ref<string>('')

const handlePriorityClick = (row: Defect) => {
  const popoverKey = `priority-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingPriority.value = row.priority || ''
  editingPopovers.value[popoverKey] = true
}

// 优先级选择后直接更新
const handlePriorityChange = (val: string) => {
  if (!editingDefectId.value) return
  if (!val) return
  
  const defectId = editingDefectId.value
  const popoverKey = `priority-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingPriority.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-priority', defectId, val)
}

// 严重程度编辑相关
const editingSeverity = ref<string>('')

const handleSeverityClick = (row: Defect) => {
  const popoverKey = `severity-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingSeverity.value = row.severity || ''
  editingPopovers.value[popoverKey] = true
}

// 严重程度选择后直接更新
const handleSeverityChange = (val: string) => {
  if (!editingDefectId.value) return
  if (!val) return
  
  const defectId = editingDefectId.value
  const popoverKey = `severity-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingSeverity.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-severity', defectId, val)
}

// 类型编辑相关
const editingType = ref<string>('')

const handleTypeClick = (row: Defect) => {
  const popoverKey = `type-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingType.value = row.type || ''
  editingPopovers.value[popoverKey] = true
}

// 类型选择后直接更新
const handleTypeChange = (val: string) => {
  if (!editingDefectId.value) return
  if (!val) return
  
  const defectId = editingDefectId.value
  const popoverKey = `type-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingType.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-type', defectId, val)
}

// 来源编辑相关
const editingSource = ref<string>('')

const handleSourceClick = (row: Defect) => {
  const popoverKey = `source-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingSource.value = row.source || ''
  editingPopovers.value[popoverKey] = true
}

// 来源选择后直接更新
const handleSourceChange = (val: string) => {
  if (!editingDefectId.value) return
  if (!val) return
  
  const defectId = editingDefectId.value
  const popoverKey = `source-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingSource.value = ''
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-source', defectId, val)
}

// 负责人编辑相关
const editingAssignee = ref<string | null>(null)

const handleAssigneeClick = (row: Defect) => {
  const popoverKey = `assignee-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingAssignee.value = row.assignee_id || null
  editingPopovers.value[popoverKey] = true
}

// 负责人选择后直接更新
const handleAssigneeChange = (val: string | null) => {
  if (!editingDefectId.value) return
  
  const defectId = editingDefectId.value
  const assigneeValue = val || null
  const popoverKey = `assignee-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingAssignee.value = null
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-assignee', defectId, assigneeValue)
}

// 报告人编辑相关
const editingReporter = ref<string | null>(null)

const handleReporterClick = (row: Defect) => {
  const popoverKey = `reporter-${row.id}`
  closeOtherPopovers(popoverKey)
  editingDefectId.value = row.id
  editingReporter.value = row.reporter_id || null
  editingPopovers.value[popoverKey] = true
}

// 报告人选择后直接更新
const handleReporterChange = (val: string | null) => {
  if (!editingDefectId.value) return
  
  const defectId = editingDefectId.value
  const reporterValue = val || null
  const popoverKey = `reporter-${defectId}`
  
  // 关闭弹窗
  editingPopovers.value[popoverKey] = false
  editingDefectId.value = null
  editingReporter.value = null
  
  // 触发更新（父组件会处理成功提示和刷新）
  emit('update-reporter', defectId, reporterValue)
}

// 同步表格选择状态
watch(
  () => props.selectedIds,
  async selectedIds => {
    await nextTick()
    if (!tableRef.value || isSyncingSelection.value) return
    
    // 检查当前表格选择状态是否已经与 selectedIds 一致
    const currentSelectedRows = tableRef.value.getSelectionRows() as Defect[]
    const currentSelectedIds = currentSelectedRows.map(row => row.id)
    const expectedSelectedIds = props.defects
      .filter(row => selectedIds.includes(row.id))
      .map(row => row.id)
    
    // 如果状态已经一致，不需要更新
    if (
      currentSelectedIds.length === expectedSelectedIds.length &&
      currentSelectedIds.every(id => expectedSelectedIds.includes(id)) &&
      expectedSelectedIds.every(id => currentSelectedIds.includes(id))
    ) {
      return
    }
    
    // 设置同步标志，防止触发 selection-change 事件
    isSyncingSelection.value = true
    
    try {
      // 先清除所有选择
      tableRef.value.clearSelection()
      // 如果没有选中的，直接返回
      if (!selectedIds.length) {
        return
      }
      // 根据 selectedIds 同步表格选择状态
      props.defects.forEach(row => {
        if (selectedIds.includes(row.id)) {
          tableRef.value?.toggleRowSelection(row, true)
        }
      })
    } finally {
      // 使用 nextTick 确保 DOM 更新完成后再重置标志
      await nextTick()
      isSyncingSelection.value = false
    }
  },
  { immediate: true, deep: true }
)

// 监听 defects 数据变化，重新同步选择状态
watch(
  () => props.defects,
  async () => {
    await nextTick()
    if (!tableRef.value || isSyncingSelection.value) return
    
    // 设置同步标志，防止触发 selection-change 事件
    isSyncingSelection.value = true
    
    try {
      // 数据变化时，重新同步选择状态
      if (!props.selectedIds.length) {
        tableRef.value.clearSelection()
        return
      }
      // 先清除所有选择
      tableRef.value.clearSelection()
      // 根据当前页面的 defects 和 selectedIds 同步选择状态
      props.defects.forEach(row => {
        if (props.selectedIds.includes(row.id)) {
          tableRef.value?.toggleRowSelection(row, true)
        }
      })
    } finally {
      // 使用 nextTick 确保 DOM 更新完成后再重置标志
      await nextTick()
      isSyncingSelection.value = false
    }
  },
  { deep: true }
)
</script>

<style scoped lang="scss">
.list-view-card {
  border-radius: 12px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
  width: 100%;
  background: #ffffff;
  position: relative;
  
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    padding: 0;
    overflow: hidden;
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  background: #fafbfc;
  flex-shrink: 0;
  
  .title {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #303133;
    
    strong {
      font-size: 16px;
      font-weight: 600;
    }
    
    .count {
      font-size: 13px;
      color: #909399;
      font-weight: 400;
    }
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .action-button {
      color: #606266;
      font-size: 13px;
      padding: 6px 12px;
      transition: all 0.2s;
      
      &:hover {
        color: #409eff;
        background-color: #ecf5ff;
      }
      
      .el-icon {
        margin-right: 4px;
        font-size: 14px;
      }
    }
  }
  
  :deep(.el-button) {
    padding: 8px 16px;
    border-radius: 6px;
    transition: all 0.2s;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
}

.defect-cell {
  padding: 4px 0;
  
  .title-row {
    margin-bottom: 6px;
    
    :deep(.el-link) {
      font-weight: 600;
      font-size: 14px;
      color: #303133;
      transition: all 0.2s;
      
      &:hover {
        color: #409eff;
        text-decoration: none;
      }
    }
  }
  
  .meta {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 12px;
    color: #909399;
    
    span {
      display: inline-flex;
      align-items: center;
      
      &:first-child {
        color: #909399;
        font-family: 'Monaco', 'Consolas', monospace;
      }
      
      &:not(:first-child) {
        padding: 2px 8px;
        background: #f0f2f5;
        border-radius: 4px;
        color: #606266;
      }
    }
  }
}

.table-footer {
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #ebeef5;
  background: #fafbfc;
  flex-shrink: 0;
  min-height: 60px;
  position: relative;
}

.table-pagination {
  margin-left: auto;
  
  :deep(.el-pagination) {
    margin: 0;
    
    .el-pagination__total {
      color: #606266;
      font-size: 13px;
      font-weight: 500;
      margin-right: 12px;
    }
    
    .el-pagination__sizes {
      margin-right: 12px;
      
      .el-select {
        .el-input__inner {
          height: 28px;
          line-height: 28px;
          font-size: 13px;
          border-radius: 4px;
          border-color: #dcdfe6;
          transition: all 0.2s;
          
          &:hover {
            border-color: #c0c4cc;
          }
        }
        
        &.is-focus .el-input__inner {
          border-color: #409eff;
        }
      }
    }
    
    .btn-prev,
    .btn-next {
      width: 28px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      background: #ffffff;
      color: #606266;
      font-size: 14px;
      transition: all 0.2s;
      
      &:hover:not(.disabled) {
        color: #409eff;
        border-color: #409eff;
        background: #ecf5ff;
      }
      
      &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        background: #f5f7fa;
      }
    }
    
    .el-pager {
      margin: 0 8px;
      
      li {
        min-width: 28px;
        height: 28px;
        line-height: 28px;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        background: #ffffff;
        color: #606266;
        font-size: 13px;
        font-weight: 500;
        margin: 0 2px;
        transition: all 0.2s;
        
        &:hover:not(.disabled):not(.is-active) {
          color: #409eff;
          border-color: #409eff;
          background: #ecf5ff;
        }
        
        &.is-active {
          color: #ffffff;
          background: #409eff;
          border-color: #409eff;
          font-weight: 600;
        }
        
        &.disabled {
          color: #c0c4cc;
          cursor: not-allowed;
          background: #f5f7fa;
        }
      }
    }
    
    // 响应式优化
    @media (max-width: 768px) {
      .el-pagination__total {
        display: none;
      }
    }
  }
  
  :deep(.el-table__inner-wrapper) {
    min-width: 0;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-table) {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    min-width: 1290px;
    width: 100%;
    border: none;
    
    .el-table__header-wrapper {
      flex-shrink: 0;
    }
    
    .el-table__body-wrapper {
      flex: 1 1 auto;
      min-height: 0;
      overflow-x: auto;
      overflow-y: auto;
    }
    
    .el-table__header {
      th {
        background: #fafbfc;
        color: #606266;
        font-weight: 600;
        font-size: 13px;
        border-bottom: 2px solid #ebeef5;
        padding: 12px 0;
        white-space: nowrap;
      }
      
      th.el-table__cell:first-child {
        text-align: center;
        
        .cell {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
    
    .el-table__body {
      tr {
        transition: background-color 0.2s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        td {
          border-bottom: 1px solid #f0f2f5;
          padding: 14px 8px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        td.el-table__cell:first-child {
          text-align: center;
          padding: 14px 0;
          
          .cell {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
      
      tr.el-table__row.current-row,
      tr.el-table__row.selected {
        background-color: #ecf5ff !important;
        
        &:hover {
          background-color: #d9ecff !important;
        }
        
        td {
          background-color: transparent;
        }
      }
      
      tr.el-table__row--striped {
        background-color: #fafbfc;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.current-row,
        &.selected {
          background-color: #e6f2ff !important;
          
          &:hover {
            background-color: #d0e7ff !important;
          }
        }
      }
    }
    
    :deep(.el-checkbox) {
      .el-checkbox__inner {
        border-color: #dcdfe6;
        transition: all 0.2s;
        
        &:hover {
          border-color: #409eff;
        }
      }
      
      &.is-checked .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
      
      &.is-indeterminate .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }
  
  :deep(.el-table__header-wrapper) {
    overflow-x: hidden;
    overflow-y: hidden;
    flex-shrink: 0;
  }
  
  :deep(.el-table__fixed-body-wrapper),
  :deep(.el-table__fixed-header-wrapper) {
    overflow-x: hidden;
    overflow-y: hidden;
  }
}


.editable-text {
  cursor: pointer;
  color: #606266;
  transition: all 0.2s;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  min-width: 60px;
  
  &:hover {
    opacity: 0.8;
  }
}

.editable-tag {
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

// Popover 样式
:deep(.defect-edit-popover) {
  padding: 8px;
  
  .popover-content {
    min-width: 180px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .popover-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 4px;
    }
  }
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .user-name {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

:deep(.el-button--text) {
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.2s;
  
  &:hover {
    background-color: #f0f2f5;
  }
  
  &.el-button--danger {
    &:hover {
      color: #f56c6c;
      background-color: #fef0f0;
    }
  }
}

.versions-cell {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  
  .more-versions {
    color: #909399;
    font-size: 12px;
  }
}

.tags-cell {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  
  .more-tags {
    color: #909399;
    font-size: 12px;
  }
}

.date-time-cell {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
</style>

